<template>
  <div class="app-container">
    <div id="app" style="width: 100%;display:inline-block">
      <el-form ref="searchForm" :model="searchForm" label-width="100px">
        <el-col :span="3">
          <el-form-item label="项目名称" label-width="70px">
            <el-input v-model="searchForm.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="客户名称" prop="customer_id" label-width="70px">
            <!--<el-input v-model="ruleForm.customer_id"></el-input>-->
            <el-select
              v-model="searchForm.customer_id"
              filterable
              remote
              reserve-keyword
              placeholder="关键词搜索，空格表示全部"
              :remote-method="remoteMethod"
              :loading="loading.customers">
              <el-option
                v-for="item in customers"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="承建公司" prop="branch_id" label-width="70px">
            <el-select v-model="searchForm.branch_id" placeholder="承建公司">
              <el-option v-for="(val, key) in branch" :key="key" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="签订状态" prop="origin_type" label-width="70px">
            <el-select v-model="searchForm.sign_status" placeholder="合同类型">
              <el-option v-for="(val, key) in contractSign" :key="key" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="合同状态" prop="progress_status" label-width="70px">
            <el-select v-model="searchForm.progress_status" placeholder="合同状态">
              <el-option v-for="(val, key) in contractStatus" :key="key" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="选择时间" prop="flow_status" label-width="70px">
            <el-date-picker
              v-model="searchForm.time"
              type="daterange"
              value-format = "timestamp"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions2">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <!--<el-form-item label="搜索" label-width="40px">-->
          <el-button @click="onSubmitSearchForm()" icon="el-icon-search" circle style="float: right;margin-right: 50%"></el-button>
          <!--</el-form-item>-->
        </el-col>
      </el-form>
    </div>
    <!--分页器-->
    <div style="padding:0 10px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="searchForm.currentPage"
        :page-sizes="[10,30,50,100]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchForm.totalCount">
      </el-pagination>
    </div>
    <table class="_table" border="0" cellpadding="0" cellspacing="0" style="width: 100%">
      <thead>
      <tr>
        <th>序号</th>
        <th width="100px">合同编号</th>
        <th width="200px">项目名称</th>
        <th>合同类型</th>
        <th>承建分公司</th>
        <th width="100px">委托单位</th>
        <th>签订时间</th>
        <th>完成时间</th>
        <th>签订状态</th>
        <th>合同状态</th>
        <th>签订状态</th>
        <th style="min-width: 196px">生产详情</th>
        <th style="min-width: 200px">操作</th>
      </tr>
      </thead>
      <tr v-for="(item, key) in list._items" :key="key">
        <td>{{item.id}}</td>
        <td>{{item.project_no}}</td>
        <td>{{item.name}}</td>
        <td>{{item.origin_type | parseOriginType}}</td>
        <td>{{item.branch_id | parseBranch}}</td>
        <td>{{item.customer_name}}</td>
        <td>{{item.sign_at | parseTime}}</td>
        <td>{{item.complete_at | parseTime}}</td>
        <td>{{item.sign_status === 0 ? '未签订' : '已签订' }}</td>
        <td>{{item.progress_status | parseProjectType}}</td>
        <td>{{item.receive_status | receiveStatus}}</td>
        <td v-if="item.flowType !== null">{{item.flowType.flow_id | flowName}}:{{item.flowType.status | productStatus}}:{{item.flowType.checkStatus | parseCheckStatus}}</td>
        <td v-else></td>
        <td><el-button @click="onDialogSign(item)" size="mini">合同签订</el-button><el-button @click="onDialogSignFinish(item)" size="mini">合同状态</el-button></td>
      </tr>
    </table>
    <div id="dialog">
      <!--签订状态日期-->
      <el-dialog
        title="请选择签订日期"
        :visible.sync="visiable.dialogVisible"
        width="30%">
        <el-form ref="ruleFormSign" :model="ruleFormSign" :rules="rules" label-width="80px">
          <el-form-item label="合同状态" prop="origin_type">
            <el-select v-model="ruleFormSign.sign_status" placeholder="请选择合同状态">
              <el-option v-for="(val, key) in SignStatus" :key="key" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="签订日期" prop="sign_at">
            <el-date-picker
              v-model="ruleFormSign.sign_at"
              type="date"
              value-format="timestamp"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button @click="visiable.dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="onSubmitForm('ruleFormSign')">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!--合同状态日期-->
      <el-dialog
        title="请选择完成日期"
        :visible.sync="visiable.DialogFinish"
        width="30%">
        <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="80px">
          <el-form-item label="合同状态" prop="origin_type">
            <el-select v-model="ruleForm.progress_status" placeholder="请选择合同状态">
              <el-option v-for="(val, key) in projectType" :key="key" :label="val.name" :value="val.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="完成日期" prop="complete_at">
            <el-date-picker
              v-model="ruleForm.complete_at"
              type="date"
              value-format="timestamp"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button @click="visiable.DialogFinish = false">取 消</el-button>
            <el-button type="primary" @click="onSubmitComplete('ruleForm')">确 定</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import { getProjects, updateProject, parseOriginType, getProject } from '../../api/project'
  import _ from 'lodash'
  import Store from '../../store'
  import { parseTime } from '../../utils'
  import { getCustomers } from '../../api/customer'
  import { getBranches } from '../../api/branch'
  import { replyRes } from '../../utils/res'

  const defaultValue = {
    id: 0,
    sign_status: 1,
    progress_status: null,
    sign_at: null,
    complete_at: null
  }

  export default {
    name: 'sign',
    data() {
      return {
        list: {},
        visiable: {
          dialogVisible: false,
          DialogFinish: false,
          DialogEdit: false
        },
        receive_status: [
          { id: 0, name: '未收款' },
          { id: 1, name: '可收款' },
          { id: 2, name: '收款中' },
          { id: 3, name: '部分收款' },
          { id: 4, name: '完成收款' }
        ],
        customers: {},
        loading: {
          customers: false,
          users: false
        },
        branch: [
          { id: null, name: '全部' }
        ], // 承建单位
        projectType: [
          { id: 0, name: '商务对接' },
          { id: 1, name: '生产中' },
          { id: 2, name: '完成生产' },
          { id: 3, name: '已完成' }
        ],
        contractStatus: [
          { id: null, name: '全部' },
          { id: 0, name: '商务对接' },
          { id: 1, name: '生产中' },
          { id: 2, name: '完成生产' },
          { id: 3, name: '已完成' }
        ],
        SignStatus: [
          { id: 0, name: '未签订' },
          { id: 1, name: '已签订' }
        ],
        contractSign: [
          { id: null, name: '全部' },
          { id: 0, name: '未签订' },
          { id: 1, name: '已签订' }
        ],
        ruleForm: Object.assign({}, defaultValue),
        ruleFormSign: Object.assign({}, defaultValue),
        rules: {
          sign_at: [
            { required: true, message: '日期不能为空', trigger: 'blur' }
          ],
          complete_at: [
            { required: true, message: '日期不能为空', trigger: 'blur' }
          ]
        },
        searchForm: {
          name: null,
          start_at: null,
          end_at: null,
          sign_status: null, // 合同签订
          progress_status: null, // 合同进度
          customer_id: null,
          branch_id: null,
          page: 1,
          pageSize: 10,
          totalCount: 0,
          time: []
        },
        pickerOptions2: {
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    },
    mounted() {
      this.fetchProjects()
      this.fetchBranches()
    },
    filters: {
      // 将id转换为合同编号
      padStr: function(value) {
        return 'hj-' + _.padStart(value, 8, '0')
      },
      parseBranch: function(value) {
        const list = Store.state.user.branches
        for (const index in list) {
          if (parseInt(list[index].id) === value) {
            return list[index].name
          }
        }
        return value
      },
      flowName: function(value) {
        if (value === 1 || value === '1') {
          return '项目建议书'
        }
        if (value === 2 || value === '2') {
          return '可研阶段'
        }
        if (value === 3 || value === '3') {
          return '初设阶段'
        }
        if (value === 4 || value === '4') {
          return '施工图阶段'
        }
        return value
      },
      productStatus: function(value) {
        if (value === 0) {
          return '未开始'
        }
        if (value === 1) {
          return '前期工作'
        }
        if (value === 2) {
          return '勘查设计'
        }
        if (value === 3) {
          return '内部校审'
        }
        if (value === 4) {
          return '概预算编制'
        }
        if (value === 5) {
          return '成果提交'
        }
        if (value === 6) {
          return '已完成'
        }
        return value
      },
      parseCheckStatus: function(value) {
        if (value === null) {
          return '未开始'
        }
        if (value === 0 || value === '0') {
          return '送校核'
        }
        if (value === 1 || value === '1') {
          return '返回设计'
        }
        if (value === 2 || value === '2') {
          return '送审核'
        }
        if (value === 3 || value === '3') {
          return '送批准'
        }
        if (value === 4 || value === '4') {
          return '返回审核'
        }
        if (value === 5 || value === '5') {
          return '已完成'
        }
        return value
      },
      parseTime: function(value) {
        if (!value) return ''
        value = value.toString()
        return parseTime(value, '{y}年{m}月{d}日')
      },
      parseOriginType,
      parseProjectType: function(value) {
        if (value === 0) {
          return '商务对接'
        }
        if (value === 1) {
          return '生产中'
        }
        if (value === 2) {
          return '完成生产'
        }
        if (value === 3) {
          return '已完成'
        }
        return value
      },
      receiveStatus: function(value) {
        if (value === 0) {
          return '未收款'
        }
        if (value === 1) {
          return '可收款'
        }
        if (value === 2) {
          return '收款中'
        }
        if (value === 3) {
          return '部分收款'
        }
        if (value === 4) {
          return '完成收款'
        }
        return value
      }
    },
    methods: {
      // 获取合同列表
      fetchProjects() {
        getProjects(this.searchForm).then(res => {
          this.list = res.data
          this.searchForm.totalCount = res.data._meta.totalCount
        })
      },
      // 获取承建公司列表
      fetchBranches() {
        getBranches().then(res => {
          for (const x in res.data) {
            this.branch.push(res.data[x])
          }
        })
      },
      fetchProject(id) {
        getProject({ id: id }).then(res => {
          res.data.complete_at > 0 ? res.data.complete_at *= 1000 : null
          res.data.sign_at > 0 ? res.data.sign_at *= 1000 : null
          this.ruleFormSign = Object.assign({}, { id: res.data.id, sign_at: res.data.sign_at, sign_status: res.data.sign_status })
          this.ruleForm = Object.assign({}, { id: res.data.id, complete_at: res.data.complete_at, progress_status: res.data.progress_status })
        })
      },
      // 打开合同签订窗口
      onDialogSign(item) {
        this.fetchProject(item.id)
        this.visiable.dialogVisible = true
      },
      // 合同状态窗口
      onDialogSignFinish(item) {
        this.fetchProject(item.id)
        this.visiable.DialogFinish = true
      },
      // 获取修改日期
      // 合同窗口确认修改
      onSubmitForm(forName) {
        this.$refs[forName].validate(valid => {
          if (valid) {
            console.log(this.ruleForm)
            this.ruleFormSign.sign_at /= 1000
            updateProject(this.ruleFormSign).then(res => {
              if (replyRes(res)) {
                this.fetchProjects()
                this.visiable.dialogVisible = false
                this.visiable.DialogFinish = false
              }
            })
          } else {
            return false
          }
        })
      },
      // 合同状态修改
      onSubmitComplete(forName) {
        this.$refs[forName].validate(valid => {
          if (valid) {
            console.log(this.ruleForm)
            this.ruleForm.complete_at /= 1000
            updateProject(this.ruleForm).then(res => {
              if (replyRes(res)) {
                this.fetchProjects()
                this.visiable.DialogFinish = false
              }
            })
          } else {
            return false
          }
        })
      },
      // 一页多少行
      handleSizeChange(pageSize) {
        this.searchForm.pageSize = pageSize
        this.fetchProjects()
      },
      // 翻页
      handlePageChange(currentPage) {
        this.searchForm.page = currentPage
        this.fetchProjects()
      },
      /** 远程搜索客户列表方法 */
      remoteMethod(query) {
        this.loading.customers = true
        let params = {}
        if (query.trim() !== '') {
          params = { name: query.trim() }
        }
        getCustomers(params).then(res => {
          this.customers = res.data._items
          this.loading.customers = false
        })
      },
      // 搜索
      onSubmitSearchForm() {
        if (this.searchForm.time !== null && this.searchForm.time.length > 0) {
          this.searchForm.start_at = this.searchForm.time[0]
          this.searchForm.end_at = this.searchForm.time[1]
        } else {
          this.searchForm.start_at = null
          this.searchForm.end_at = null
        }
        this.fetchProjects()
      }
    }
  }
</script>

<style scoped>

</style>
